package com.wangshouyu.mp.pay.common.utils;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author 王守钰
 * @program wsy-mp-pay
 * @date 2020年08月15日 01:09
 * @description: 解密工具
 */
public class AesUtils {

    private AesUtils(){}

    private static final String UTF8 = "UTF-8";

    static final int KEY_LENGTH_BYTE = 32;
    static final int TAG_LENGTH_BIT = 128;

    /**
     * 解密字符串
     * @param aesKey
     * @param associatedData
     * @param nonce
     * @param cipherText
     * @return
     * @throws GeneralSecurityException
     * @throws IOException
     */
    public static String decryptToString(String aesKey, String associatedData, String nonce, String cipherText)
            throws GeneralSecurityException, IOException {
        byte[] keys = {};
        if ((keys = aesKey.getBytes(UTF8)).length != KEY_LENGTH_BYTE) {
            throw new IllegalArgumentException("无效的ApiV3Key，长度必须为32个字节");
        }
        try {
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

            SecretKeySpec key = new SecretKeySpec(keys, "AES");
            GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce.getBytes(UTF8));

            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            cipher.updateAAD(associatedData.getBytes(UTF8));

            return new String(cipher.doFinal(Base64.getDecoder().decode(cipherText)), UTF8);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
